const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');

// 定义公告模型
const Announcement = sequelize.define('Announcement', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: { msg: '公告标题不能为空' },
      len: { args: [3, 100], msg: '公告标题长度必须在3-100个字符之间' }
    }
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
    validate: {
      notEmpty: { msg: '公告内容不能为空' }
    }
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
    allowNull: false
  },
  createdBy: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  }
}, {
  tableName: 'announcements',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['created_by'] },
    { fields: ['is_active'] },
    { fields: ['created_at'] }
  ]
});

// 关联关系
Announcement.associate = (models) => {
  // 公告属于创建者
  Announcement.belongsTo(models.User, { foreignKey: 'createdBy', as: 'creator' });
};

module.exports = Announcement;